<template>
  <div>
    <Breadcrumb :opt-data="genParamOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="genParamData"
          :custom-empty="true"
          @pageChanged="getGenParamData"
          @sizeChanged="getGenParamData"
          @filterChange="getGenParamData">
          <EmptyContent slot="empty" :opt-data="genParamOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditGenParam ? '新增' : '编辑'}通用参数名`"
        :visible.sync="showGenParamDialog"
        :close-on-click-modal="false"
        width="600px"
        center>
        <el-form
          v-loading="genParamFormLoading"
          :ref="genParamFormRef"
          :model="genParamForm"
          :rules="genParamFormRules"
          size="small"
          label-width="130px">
          <el-form-item label="设备类别" prop="deviceType">
            <el-select v-model="genParamForm.deviceType" clearable filterable class="width-100"
                       placeholder="请选择设备类别">
              <el-option :label="deviceType.label" :value="deviceType.value" :key="idx"
                         v-for="(deviceType, idx) in deviceTypeData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型" prop="type">
            <el-radio-group v-model="genParamForm.type">
              <el-radio :label="type.value" :key="idx" v-for="(type, idx) in commonConfig.genParamType">
                {{type.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参数名" prop="name">
            <el-input v-model="genParamForm.name" placeholder="请填写参数名"></el-input>
          </el-form-item>
          <el-form-item label="参数别名" prop="alias">
            <el-input v-model="genParamForm.alias" placeholder="请填写参数别名"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="genParamForm.remarks" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="genParamFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="genParamFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {commonString, msgCode} from "@/config/string";
  import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import generalParamTableCfg from "@/config/table/generalParam";
  import EZTable from '@/components/table/EZTable';

  export default {
    name: "GeneralParam",
    components: {
      EZTable
    },
    data() {
      return {
        commonConfig: commonConfig,
        tableLoading: true,
        tableId: tableIdConfig.generalParam,
        tableHdl: null,
        genParamData: [],
        showGenParamDialog: false,
        genParamFormLoading: false,
        deviceTypeData: [],
        genParamForm: {},
        genParamFormRules: {
          deviceType: [
            {required: true, message: '请选择设备类别', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择命令类型', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请填写参数名', trigger: 'blur'}
          ],
          alias: [
            {required: true, message: '请填写参数别名', trigger: 'blur'}
          ],
        },
        genParamFormRef: 'genParamFormRef',
        isEditGenParam: false
      }
    },
    computed: {
      genParamOptData() {
        return [
          {
            type: 'btn',
            label: '新增通用参数名',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initGenParamForm();
      this.getDeviceTypeData();
      this.getGenParamData();
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, generalParamTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const generalParam = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showGenParamDialog = true;
              this.isEditGenParam = true;
              this.genParamForm = generalParam;
              break;
            case tableOptBtnConfig.copy.type:
              this.showGenParamDialog = true;
              this.isEditGenParam = false;
              this.genParamForm = generalParam;
              delete this.genParamForm['_id'];
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteGenParam(generalParam);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initGenParamForm() {
        this.genParamForm = {
          deviceType: '',
          type: commonConfig.genParamType[0].value,
          name: '',
          alias: '',
          remarks: '',
        }
      },
      resetGenParamForm() {
        this.initGenParamForm();
        const genParamForm = this.$refs[this.genParamFormRef];
        genParamForm && genParamForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditGenParam && this.resetGenParamForm();
        this.showGenParamDialog = true;
        this.isEditGenParam = false;
      },
      getDeviceTypeData() {
        API.deviceType.deviceTypeAll().then(result => {
          const {data = []} = result;
          this.deviceTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getGenParamData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.genParam.genParamList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          this.genParamData = result.data.map(d => {
            const genParamType = commonConfig.genParamType.find(skt => {
              return skt.value === d.type
            }) || {};
            return {...d, typeText: genParamType.label || commonString.unknown}
          });
          this.tableHdl.total = result.total || 0;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteGenParam(genParam = {}) {
        confirmHandle({label: `确定要删除通用参数名：${genParam.name} 吗?`}).then(() => {
          API.genParam.genParamDelete({_id: genParam._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '通用参数名'});
            this.tableHdl.judgeTableMatched();
            this.getGenParamData();
            this.resetGenParamForm();
          });
        }).catch(() => {
        });
      },
      genParamFormCanceled() {
        this.showGenParamDialog = false;
      },
      genParamFormSubmitted() {
        this.$refs[this.genParamFormRef].validate((valid) => {
          if (!valid) return;
          this.genParamFormLoading = true;
          if (!this.isEditGenParam) {
            API.genParam.genParamAdd({...this.genParamForm}).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '通用参数名'});
              this.showGenParamDialog = false;
              this.genParamFormLoading = false;
              this.getGenParamData();
              this.resetGenParamForm();
            }).catch(err => {
              console.log('err', err)
              this.genParamFormLoading = false;
            });
          } else {
            API.genParam.genParamEdit({...this.genParamForm}).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '通用参数名'});
              this.showGenParamDialog = false;
              this.genParamFormLoading = false;
              this.getGenParamData();
              this.resetGenParamForm();
            }).catch(err => {
              console.log('err', err)
              this.genParamFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
